<script setup lang="ts">
import {ref, onMounted, watch} from 'vue'
import {Setting, ArrowDown, Plus, Edit, Delete, Loading, Operation, DeleteFilled, CaretRight, CaretBottom} from '@element-plus/icons-vue'
import {ElDialog, ElMessageBox} from 'element-plus'
import SettingsDialog from './SettingsDialog.vue'
import ModelServiceDialog from './ModelServiceDialog.vue'
import {ElMessage} from 'element-plus'
import {MdPreview} from 'md-editor-v3';
import 'md-editor-v3/lib/preview.css';

import ajax from "../main.ts";
import baseUrl from "../api.ts";

interface Tool {
  id: number
  name: string
}

interface SmartAgent {
  id: number
  name: string
  description: string
  enabled: string
  isPublic: string
  mcpTools: (string | number)[]
}

interface AgentOption {
  value: string
  label: string
  description: string
  enabled: string
}

interface ModelOption {
  value: string
  label: string
  enabled: string
}

interface BaseResponse {
  code: number
  msg: string
}

interface ApiResponse<T> extends BaseResponse {
  data: T
}

interface MCPTool {
  value: string | number
  label: string
}

interface ToolCall {
  tool: string
  args: string
}

interface ChatMessage {
  id: number
  content: string
  isUser: boolean
  isLoading?: boolean
  toolCalls?: ToolCall[] // 添加工具调用数组
}

interface ChatResponse {
  content: string
}

interface Topic {
  id: number
  title: string
  isNew: boolean
  isDefault?: boolean
}

const isAgentDropdownVisible = ref(false)
const isModelDropdownVisible = ref(false)
const isAddAgentDialogVisible = ref(false)
const isSettingsDialogVisible = ref(false)
const isEditAgentDialogVisible = ref(false)
const isModelServiceDialogVisible = ref(false)
const newAgentName = ref('')
const newAgentDescription = ref('')
const newAgentEnabled = ref("1")
const newAgentIsPublic = ref("0")
const newAgentMCPTools = ref<(string | number)[]>([])
const mcpTools = ref<MCPTool[]>([])
const isLoadingTools = ref(false)
const agents = ref<AgentOption[]>([])
const models = ref<ModelOption[]>([])
const selectedAgent = ref('')
const selectedModel = ref('')
const editAgentId = ref('')
const editAgentName = ref('')
const editAgentDescription = ref('')
const editAgentEnabled = ref("1")
const editAgentIsPublic = ref("0")
const editAgentMCPTools = ref<(string | number)[]>([])

const topics = ref<Topic[]>([])
const currentTopicId = ref<number>(1)

const messages = ref<ChatMessage[]>([])
const newMessage = ref('')
const isLoading = ref(false)
const chatMessagesRef = ref<HTMLElement | null>(null)
const expandedTools = ref<Record<number, Record<number, boolean>>>({}) // 用于跟踪展开状态的对象：{消息ID: {工具索引: 是否展开}}

const agentFormRef = ref()
const editAgentFormRef = ref()

const agentFormRules = {
  name: [
    {required: true, message: '请输入智能体名称', trigger: 'blur'},
    {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
  ]
}

// 切换工具调用的展开状态
const toggleToolExpanded = (messageId: number, toolIndex: number) => {
  if (!expandedTools.value[messageId]) {
    expandedTools.value[messageId] = {}
  }
  expandedTools.value[messageId][toolIndex] = !expandedTools.value[messageId][toolIndex]
}

// 检查工具调用是否展开
const isToolExpanded = (messageId: number, toolIndex: number): boolean => {
  return expandedTools.value[messageId]?.[toolIndex] || false
}

const selectAgent = (agent: { value: string; label: string; description: string }) => {
  selectedAgent.value = agent.label
  isAgentDropdownVisible.value = false
}

const selectModel = (agent: { value: string; label: string; enabled: string }) => {
  selectedModel.value = agent.label
  isModelDropdownVisible.value = false
}

// 获取MCP工具列表
const fetchMCPTools = async () => {
  try {
    isLoadingTools.value = true
    const response = await ajax.get('getTools/') as ApiResponse<ApiResponse<Tool[]>>
    if (response.data.code !== 200) {
      ElMessage.error(response.data.msg)
      return
    }
    mcpTools.value = response.data.data.map(tool => ({
      value: tool.id,
      label: tool.name
    }))
  } catch (error) {
    console.log(error)
    ElMessage.error('获取工具列表失败，请稍后重试')
  } finally {
    isLoadingTools.value = false
  }
}

// 获取智能体列表
const fetchSmartAgents = async () => {
  try {
    const response = await ajax.get('getSmart/') as ApiResponse<ApiResponse<SmartAgent[]>>
    if (response.data.code !== 200) {
      ElMessage.error(response.data.msg)
      return
    }
    if (response.data.data) {
      agents.value = response.data.data.map(agent => ({
        value: agent.id.toString(),
        label: agent.name,
        description: agent.description,
        enabled: agent.enabled
      }))
      if (agents.value.length > 0) {
        selectedAgent.value = agents.value[0].label
      }
    }
  } catch (error) {
    console.log(error)
    ElMessage.error('获取智能体列表失败，请稍后重试')
  }
}


const fetchSmartModels = async () => {
  try {
    const response = await ajax.get('getSmartModel/') as ApiResponse<ApiResponse<SmartAgent[]>>
    if (response.data.code !== 200) {
      ElMessage.error(response.data.msg)
      return
    }
    if (response.data.data) {
      models.value = response.data.data.map(agent => ({
        value: agent.id.toString(),
        label: agent.name,
        enabled: agent.enabled
      }))
      if (models.value.length > 0) {
        selectedModel.value = models.value[0].label
      }
    }
  } catch (error) {
    console.log(error)
    ElMessage.error('获取智能体列表失败，请稍后重试')
  }
}

// 监听对话框显示状态
const handleDialogOpen = () => {
  fetchMCPTools()
  // 重置表单
  newAgentName.value = ''
  newAgentDescription.value = ''
  newAgentEnabled.value = "1"
  newAgentIsPublic.value = "0"
  newAgentMCPTools.value = []
}

const handleAddAgent = async () => {
  if (!agentFormRef.value) return

  try {
    await agentFormRef.value.validate()
    const agentData: Omit<SmartAgent, 'id'> = {
      name: newAgentName.value,
      description: newAgentDescription.value,
      enabled: newAgentEnabled.value,
      isPublic: newAgentIsPublic.value,
      mcpTools: newAgentMCPTools.value
    }

    try {
      const response = await ajax.post('subSmart/', agentData) as ApiResponse<ApiResponse<null>>
      if (response.data.code !== 200) {
        ElMessage.error(response.data.msg)
        return
      }
      ElMessage.success(response.data.msg)

      // 重置表单
      newAgentName.value = ''
      newAgentDescription.value = ''
      newAgentEnabled.value = "1"
      newAgentIsPublic.value = "0"
      newAgentMCPTools.value = []
      isAddAgentDialogVisible.value = false

      // 刷新智能体列表
      await fetchSmartAgents()
    } catch (error) {
      console.log(error)
      ElMessage.error('新增智能体失败，请稍后重试')
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 从 localStorage 加载话题列表
const loadTopics = () => {
  const savedTopics = localStorage.getItem('chatTopics')
  if (savedTopics) {
    try {
      topics.value = JSON.parse(savedTopics)
    } catch (error) {
      console.error('解析话题列表失败:', error)
      topics.value = [{
        id: 1,
        title: '默认话题',
        isNew: false,
        isDefault: true
      }]
    }
  } else {
    // 如果没有保存的话题，创建默认话题
    topics.value = [{
      id: 1,
      title: '默认话题',
      isNew: false,
      isDefault: true
    }]
  }
  currentTopicId.value = topics.value[0].id
  saveTopics()
}

// 保存话题列表到 localStorage
const saveTopics = () => {
  try {
    localStorage.setItem('chatTopics', JSON.stringify(topics.value))
  } catch (error) {
    console.error('保存话题列表失败:', error)
  }
}

// 创建新话题
const createNewTopic = () => {
  const newId = Math.max(...topics.value.map(t => t.id)) + 1
  // 找到所有非默认话题
  const nonDefaultTopics = topics.value.filter(t => !t.isDefault)
  // 提取所有序号
  const numbers = nonDefaultTopics.map(t => {
    const match = t.title.match(/新对话 (\d+)/)
    return match ? parseInt(match[1]) : 0
  })
  // 找到最大的序号
  const maxNumber = Math.max(...numbers, 0)
  const newTopic: Topic = {
    id: newId,
    title: `新对话 ${maxNumber + 1}`,
    isNew: true
  }
  
  // 找到默认话题的索引
  const defaultTopicIndex = topics.value.findIndex(t => t.isDefault)
  if (defaultTopicIndex !== -1) {
    // 在默认话题后面插入新话题
    topics.value.splice(defaultTopicIndex + 1, 0, newTopic)
  } else {
    // 如果没有默认话题，则添加到末尾
    topics.value.push(newTopic)
  }
  
  // 如果话题数量超过10个（不包括默认话题），删除最旧的话题
  if (nonDefaultTopics.length > 10) {
    // 找到要删除的话题（序号1的话题）
    // 先找到所有非默认话题
    const topicsToCheck = topics.value.filter(t => !t.isDefault)
    // 按创建时间排序（假设id越大创建时间越晚）
    topicsToCheck.sort((a, b) => a.id - b.id)
    // 找到最早创建的话题
    const topicToDelete = topicsToCheck[0]
    if (topicToDelete) {
      // 删除话题的聊天记录
      deleteTopicChatHistory(topicToDelete.id)
      // 从话题列表中删除
      const index = topics.value.findIndex(t => t.id === topicToDelete.id)
      if (index !== -1) {
        topics.value.splice(index, 1)
      }
    }
  }
  
  currentTopicId.value = newId
  saveTopics()
  
  // 加载新话题的聊天记录
  loadChatHistory()
}

// 更新话题标题
const updateTopicTitle = (topicId: number, firstMessage: string) => {
  const topic = topics.value.find(t => t.id === topicId)
  if (topic && !topic.isDefault) {
    // 取前15个字符，如果超过则添加省略号
    const title = firstMessage.length > 15
      ? firstMessage.slice(0, 15) + '...'
      : firstMessage
    topic.title = title
    saveTopics()
  }
}

// 删除话题的聊天记录
const deleteTopicChatHistory = (topicId: number) => {
  try {
    localStorage.removeItem(`chatMessages_${topicId}`)
  } catch (error) {
    console.error('删除聊天记录失败:', error)
  }
}

// 修改删除话题函数
const deleteTopic = (topic: Topic) => {
  if (topic.isDefault) {
    ElMessage.warning('默认话题不可删除')
    return
  }

  ElMessageBox.confirm(
    `确定要删除话题"${topic.title}"吗？此操作将同时删除该话题的所有聊天记录。`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    const index = topics.value.findIndex(t => t.id === topic.id)
    if (index !== -1) {
      // 删除话题的聊天记录
      deleteTopicChatHistory(topic.id)

      // 如果删除的是当前话题，先切换到其他话题
      if (currentTopicId.value === topic.id) {
        // 优先切换到默认话题，如果没有则切换到第一个话题
        const defaultTopic = topics.value.find(t => t.isDefault)
        if (defaultTopic) {
          currentTopicId.value = defaultTopic.id
        } else if (topics.value.length > 1) {
          // 如果还有其他话题，切换到第一个
          currentTopicId.value = topics.value[0].id
        }
        // 加载新话题的聊天记录
        loadChatHistory()
      }

      // 删除话题
      topics.value.splice(index, 1)
      saveTopics()
      ElMessage.success('话题已删除')
    }
  }).catch(() => {})
}

// 修改切换话题函数
const switchTopic = (topic: Topic) => {
  if (currentTopicId.value === topic.id) return

  currentTopicId.value = topic.id
  // 加载对应话题的聊天记录
  loadChatHistory()
}

// 修改 loadChatHistory 函数
const loadChatHistory = () => {
  const savedMessages = localStorage.getItem(`chatMessages_${currentTopicId.value}`)
  if (savedMessages) {
    try {
      messages.value = JSON.parse(savedMessages)
    } catch (error) {
      console.error('解析聊天记录失败:', error)
      messages.value = []
    }
  } else {
    // 如果没有历史记录，设置默认消息
    messages.value = [
      {
        id: 1,
        content: 'Hello!',
        isUser: true
      },
      {
        id: 2,
        content: 'Hi,有什么可以帮助你的吗？',
        isUser: false
      }
    ]
  }
}

// 修改 saveChatHistory 函数
const saveChatHistory = () => {
  try {
    localStorage.setItem(`chatMessages_${currentTopicId.value}`, JSON.stringify(messages.value))
  } catch (error) {
    console.error('保存聊天记录失败:', error)
  }
}

// 修改 clearChatHistory 函数
const clearChatHistory = () => {
  ElMessageBox.confirm(
    '确定要清除当前话题的聊天记录吗？此操作不可恢复。',
    '清除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    messages.value = [
      {
        id: 1,
        content: 'Hello!',
        isUser: true
      },
      {
        id: 2,
        content: 'Hi,有什么可以帮助你的吗？',
        isUser: false
      }
    ]
    saveChatHistory()
    ElMessage.success('聊天记录已清除')
  }).catch(() => {})
}

// 添加滚动到底部的函数
const scrollToBottom = () => {
  setTimeout(() => {
    if (chatMessagesRef.value) {
      chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight
    }
  }, 100)
}

// 监听消息变化
watch(messages, () => {
  scrollToBottom()
}, { deep: true })

const isProcessingMessage = ref(false)

const sendMessage = async () => {
  if (!newMessage.value.trim() || isLoading.value) return

  try {
    isLoading.value = true
    isProcessingMessage.value = true // 设置正在处理消息状态
    // 添加用户消息
    const userMessage: ChatMessage = {
      id: messages.value.length + 1,
      content: newMessage.value,
      isUser: true
    }
    messages.value.push(userMessage)
    scrollToBottom() // 发送消息后滚动

    // 如果是新话题的第一条消息，更新话题标题
    const currentTopic = topics.value.find(t => t.id === currentTopicId.value)
    if (currentTopic?.isNew) {
      // 取用户消息的前15个字符，如果超过则添加省略号
      const title = newMessage.value.length > 15
        ? newMessage.value.slice(0, 15) + '...'
        : newMessage.value
      currentTopic.title = title
      currentTopic.isNew = false
      saveTopics()
    }

    // 立即清空输入框
    const currentMessage = newMessage.value
    newMessage.value = ''

    saveChatHistory()

    // 创建AI回复消息
    const aiMessage: ChatMessage = {
      id: messages.value.length + 1,
      content: '',
      isUser: false,
      isLoading: true,
      toolCalls: [] // 初始化工具调用数组
    }
    messages.value.push(aiMessage)
    scrollToBottom() // AI开始回复时滚动

    // 获取最近的10轮对话（包括当前消息）
    const recentMessages = messages.value.slice(-20) // 每轮对话包含用户和AI两条消息，所以取最后20条

    // 获取当前选中的模型和智能体信息
    const currentModel = models.value.find(m => m.label === selectedModel.value)
    const currentAgent = agents.value.find(a => a.label === selectedAgent.value)

    // 使用流式接口获取回复
    const response = await fetch(baseUrl + 'chatMsg/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'USERNAME': localStorage.getItem('userid') || '',
        'AUTHORIZATION': localStorage.getItem('token') || ''
      },
      body: JSON.stringify({
        messages: recentMessages.map(msg => ({
          content: msg.content,
          role: msg.isUser ? 'user' : 'assistant'
        })),
        model: {
          id: currentModel?.value || '',
          name: currentModel?.label || ''
        },
        agent: {
          id: currentAgent?.value || '',
          name: currentAgent?.label || ''
        }
      })
    })

    if (!response.ok) {
      throw new Error('请求失败')
    }

    const reader = response.body?.getReader()
    if (!reader) {
      throw new Error('无法获取响应流')
    }

    // 添加打字机效果
    let currentText = ''
    while (true) {
      const { done, value } = await reader.read()
      if (done) break

      // 将接收到的数据添加到AI消息中
      const text = new TextDecoder().decode(value)

      try {
        // 尝试解析JSON数据
        const jsonData = JSON.parse(text)
        
        // 处理工具调用数据
        if (jsonData.tool && jsonData.args) {
          // 如果是工具调用
          if (!aiMessage.toolCalls) {
            aiMessage.toolCalls = []
          }
          
          aiMessage.toolCalls.push({
            tool: jsonData.tool,
            args: jsonData.args
          })
        } 
        // 处理普通回复数据
        else if (jsonData.data) {
          currentText += jsonData.data
          aiMessage.content = currentText
        }
        
        // 强制更新视图
        messages.value = [...messages.value]
        saveChatHistory()
        scrollToBottom() // 每次更新内容时滚动
      } catch (e) {
        // 如果不是JSON格式，直接使用文本
        currentText += text
        aiMessage.content = currentText
        // 强制更新视图
        messages.value = [...messages.value]
        saveChatHistory()
        scrollToBottom() // 每次更新内容时滚动
      }
    }
    
    // 回复完成后，移除loading状态
    aiMessage.isLoading = false
  } catch (error) {
    console.log(error)
    ElMessage.error('发送消息失败，请稍后重试')
  } finally {
    isLoading.value = false
    isProcessingMessage.value = false // 处理完成后重置状态
  }
}

const handleEditAgent = async (agent: AgentOption) => {
  try {
    const response = await ajax.post(`getAgentDetail/`, {id: agent.value}) as ApiResponse<ApiResponse<SmartAgent>>
    if (response.data.code !== 200) {
      ElMessage.error(response.data.msg)
      return
    }

    const agentData = response.data.data
    editAgentId.value = agentData.id.toString()
    editAgentName.value = agentData.name
    editAgentDescription.value = agentData.description
    editAgentEnabled.value = agentData.enabled
    editAgentIsPublic.value = agentData.isPublic
    editAgentMCPTools.value = agentData.mcpTools
    
    // 处理类型错误，将response.data.mcp改为从其他地方获取工具列表
    fetchMCPTools()
    isEditAgentDialogVisible.value = true
  } catch (error) {
    console.log(error)
    ElMessage.error('获取智能体详情失败，请稍后重试')
  }
}

const handleUpdateAgent = async () => {
  if (!editAgentFormRef.value) return

  try {
    await editAgentFormRef.value.validate()
    const agentData: SmartAgent = {
      id: parseInt(editAgentId.value),
      name: editAgentName.value,
      description: editAgentDescription.value,
      enabled: editAgentEnabled.value,
      isPublic: editAgentIsPublic.value,
      mcpTools: editAgentMCPTools.value
    }

    try {
      const response = await ajax.post('updateAgent/', agentData) as ApiResponse<ApiResponse<null>>
      if (response.data.code !== 200) {
        ElMessage.error(response.data.msg)
        return
      }
      ElMessage.success(response.data.msg)

      // 重置表单
      editAgentName.value = ''
      editAgentDescription.value = ''
      editAgentEnabled.value = "1"
      editAgentIsPublic.value = "0"
      editAgentMCPTools.value = []
      isEditAgentDialogVisible.value = false

      // 刷新智能体列表
      await fetchSmartAgents()
    } catch (error) {
      console.log(error)
      ElMessage.error('更新智能体失败，请稍后重试')
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const handleDeleteAgent = (agent: AgentOption) => {
  ElMessageBox.confirm(
    `确定要删除智能体"${agent.label}"吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const response = await ajax.post('delAgent/', { id: agent.value }) as ApiResponse<ApiResponse<null>>
      if (response.data.code !== 200) {
        ElMessage.error(response.data.msg)
        return
      }
      ElMessage.success(response.data.msg)
      // 刷新智能体列表
      await fetchSmartAgents()
    } catch (error) {
      console.log(error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }).catch(() => {})
}

const handleModelService = () => {
  isModelServiceDialogVisible.value = true
}

onMounted(() => {
  fetchSmartAgents()
  fetchSmartModels()
  loadTopics() // 先加载话题列表
  loadChatHistory() // 再加载当前话题的聊天记录
})
</script>

<template>
  <div class="chat-container">
    <!-- 顶部选择器区域 -->
    <div class="top-selectors">
      <!-- AI模型选择区域 -->
      <div class="agent-selector-ai">
        <div class="agent-select-wrapper">
          <div class="agent-select-content">
            <div class="agent-select-input" @click="isModelDropdownVisible = !isModelDropdownVisible">
              <span class="agent-label">{{ selectedModel }}</span>
              <div class="agent-indicator">
                <div class="agent-dot"></div>
              </div>
              <el-icon class="dropdown-icon">
                <ArrowDown/>
              </el-icon>
            </div>
            <div class="agent-dropdown" v-show="isModelDropdownVisible">
              <div
                  v-for="agent in models"
                  :key="agent.value"
                  class="agent-option"
                  :class="{
                  'selected': agent.label === selectedModel,
                  'disabled': agent.enabled === '0'
                }"
              >
                <div class="agent-info" @click="agent.enabled === '1' && selectModel(agent)">
                  <span class="agent-name">{{ agent.label }}</span>
                </div>
                <div
                    class="agent-dot"
                    :class="{ 'enabled': agent.enabled === '1', 'disabled': agent.enabled === '0' }"
                ></div>

              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 智能体选择区域 -->
      <div class="agent-selector">
        <div class="agent-select-wrapper">
          <div class="agent-select-content">
            <div class="agent-select-input" @click="isAgentDropdownVisible = !isAgentDropdownVisible">
              <span class="agent-label">{{ selectedAgent }}</span>
              <div class="agent-indicator">
                <div class="agent-dot"></div>
              </div>
              <el-icon class="dropdown-icon">
                <ArrowDown/>
              </el-icon>
            </div>
            <div class="agent-dropdown" v-show="isAgentDropdownVisible">
              <div
                  v-for="agent in agents"
                  :key="agent.value"
                  class="agent-option"
                  :class="{
                  'selected': agent.label === selectedAgent,
                  'disabled': agent.enabled === '0'
                }"
              >
                <div class="agent-info" @click="agent.enabled === '1' && selectAgent(agent)">
                  <span class="agent-name">{{ agent.label }}</span>
                  <span class="agent-desc" :title="agent.description">{{ agent.description }}</span>
                </div>
                <div class="agent-actions">
                  <el-icon class="action-icon edit-icon" @click="handleEditAgent(agent)">
                    <Edit/>
                  </el-icon>
                  <el-icon class="action-icon delete-icon" @click="handleDeleteAgent(agent)">
                    <Delete/>
                  </el-icon>
                </div>
                <div
                    class="agent-dot"
                    :class="{ 'enabled': agent.enabled === '1', 'disabled': agent.enabled === '0' }"
                ></div>

              </div>
              <div class="add-agent-btn" @click="isAddAgentDialogVisible = true">
                <el-icon>
                  <Plus/>
                </el-icon>
                <span>新增智能体</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 左侧话题列表 -->
    <div class="topics-sidebar">
      <div class="topics-header">
        <h2>话题列表</h2>
        <button class="new-topic-btn" @click="createNewTopic">新建话题</button>
      </div>
      <div class="topics-list">
        <div
            v-for="topic in topics"
            :key="topic.id"
            class="topic-item"
            :class="{
              'new-topic': topic.isNew,
              'active': topic.id === currentTopicId,
              'default-topic': topic.isDefault
            }"
            @click="switchTopic(topic)"
        >
          <div class="topic-content">
            <div class="topic-icon">
              <el-icon v-if="topic.isDefault"><Setting /></el-icon>
              <el-icon v-else-if="topic.isNew"><Plus /></el-icon>
              <el-icon v-else><ChatDotRound /></el-icon>
            </div>
            <div class="topic-info">
              <span class="topic-title">{{ topic.title }}</span>
              <span class="topic-status" v-if="topic.isNew">新对话</span>
            </div>
          </div>
          <el-icon
            v-if="!topic.isDefault"
            class="delete-topic-icon"
            @click.stop="deleteTopic(topic)"
          >
            <Delete />
          </el-icon>
        </div>
      </div>
      <div class="settings-section">
        <button class="settings-btn" @click="isSettingsDialogVisible = true">
          <el-icon>
            <Setting/>
          </el-icon>
          <span>MCP设置</span>
        </button>
        <button class="settings-btn model-service-btn" @click="handleModelService">
          <el-icon>
            <Operation/>
          </el-icon>
          <span>模型服务</span>
        </button>
        <button class="settings-btn clear-chat-btn" @click="clearChatHistory">
          <el-icon>
            <DeleteFilled/>
          </el-icon>
          <span>清除聊天记录</span>
        </button>
      </div>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-main">
      <div class="chat-content">
        <div class="chat-messages" ref="chatMessagesRef">
          <div
              v-for="(message, index) in messages"
              :key="message.id"
              class="message"
              :class="{ 
                'user-message': message.isUser,
                'loading': message.isLoading && index === messages.length - 1
              }"
          >
            <!-- 工具调用区域 -->
            <div v-if="message.toolCalls && message.toolCalls.length > 0" class="tool-calls-section">
              <div v-for="(toolCall, toolIndex) in message.toolCalls" :key="toolIndex" class="tool-call-item">
                <div 
                  class="tool-call-header" 
                  @click="toggleToolExpanded(message.id, toolIndex)"
                >
                  <el-icon class="tool-icon">
                    <CaretRight v-if="!isToolExpanded(message.id, toolIndex)" />
                    <CaretBottom v-else />
                  </el-icon>
                  <span class="tool-name">{{ toolCall.tool }}</span>
                </div>
                <div 
                  class="tool-call-content" 
                  v-show="isToolExpanded(message.id, toolIndex)"
                >
                  <pre class="tool-args">{{ toolCall.args }}</pre>
                </div>
              </div>
            </div>
            
            <!-- 消息内容区域 -->
            <MdPreview v-if="message.content" :modelValue="message.content" class="md-preview"/>
          </div>
        </div>

        <!-- 输入框区域 -->
        <div class="chat-input">
          <div class="input-area">
            <textarea
                v-model="newMessage"
                placeholder="输入消息..."
                @keyup.enter="!isProcessingMessage && sendMessage()"
                :disabled="isLoading"
            ></textarea>
          </div>
          <button
            class="send-button"
            @click="sendMessage"
            :disabled="isLoading || !newMessage.trim() || isProcessingMessage"
          >
            <svg v-if="!isLoading" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none"
                 stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <line x1="22" y1="2" x2="11" y2="13"></line>
              <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
            </svg>
            <el-icon v-else class="is-loading">
              <Loading />
            </el-icon>
          </button>
        </div>
      </div>
    </div>
  </div>

  <SettingsDialog v-model:visible="isSettingsDialogVisible"/>
  <ModelServiceDialog v-model:visible="isModelServiceDialogVisible"/>

  <!-- 新增智能体对话框 -->
  <el-dialog
      v-model="isAddAgentDialogVisible"
      title="新增智能体"
      class="agent-dialog"
      width="520px"
      destroy-on-close
      @open="handleDialogOpen"
  >
    <el-form :model="{name: newAgentName, description: newAgentDescription, enabled: newAgentEnabled, isPublic: newAgentIsPublic, mcpTools: newAgentMCPTools}" ref="agentFormRef" :rules="agentFormRules" label-position="top" class="agent-form">
      <el-form-item label="智能体名称" prop="name">
        <el-input 
          v-model="newAgentName" 
          placeholder="请输入智能体名称"
        ></el-input>
      </el-form-item>
      
      <el-form-item label="功能描述" prop="description">
        <el-input 
          type="textarea" 
          v-model="newAgentDescription" 
          placeholder="请描述智能体的功能和使用场景"
          :rows="3"
          resize="none"
        ></el-input>
      </el-form-item>
      
      <div class="form-grid">
        <el-form-item label="状态设置">
          <el-radio-group v-model="newAgentEnabled">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="访问权限">
          <el-radio-group v-model="newAgentIsPublic">
            <el-radio label="1">公开</el-radio>
            <el-radio label="0">私有</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
      
      <el-form-item label="关联工具">
        <el-select
            v-model="newAgentMCPTools"
            multiple
            filterable
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="3"
            placeholder="请选择关联工具"
            class="tools-select"
            :loading="isLoadingTools"
        >
          <el-option
              v-for="item in mcpTools"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          ></el-option>
        </el-select>
        <div class="form-item-tip" v-if="newAgentMCPTools.length > 0">已选择 {{ newAgentMCPTools.length }} 项</div>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="agent-dialog-footer">
        <el-button @click="isAddAgentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddAgent">创建</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 编辑智能体对话框 -->
  <el-dialog
      v-model="isEditAgentDialogVisible"
      title="编辑智能体"
      class="agent-dialog"
      width="520px"
      destroy-on-close
  >
    
    <el-form :model="{name: editAgentName, description: editAgentDescription, enabled: editAgentEnabled, isPublic: editAgentIsPublic, mcpTools: editAgentMCPTools}" ref="editAgentFormRef" :rules="agentFormRules" label-position="top" class="agent-form">
      <el-form-item label="智能体名称" prop="name">
        <el-input 
          v-model="editAgentName" 
          placeholder="请输入智能体名称"
        ></el-input>
      </el-form-item>
      
      <el-form-item label="功能描述" prop="description">
        <el-input 
          type="textarea" 
          v-model="editAgentDescription" 
          placeholder="请描述智能体的功能和使用场景"
          :rows="3"
          resize="none"
        ></el-input>
      </el-form-item>
      
      <div class="form-grid">
        <el-form-item label="状态设置">
          <el-radio-group v-model="editAgentEnabled">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="访问权限">
          <el-radio-group v-model="editAgentIsPublic">
            <el-radio label="1">公开</el-radio>
            <el-radio label="0">私有</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
      
      <el-form-item label="关联工具">
        <el-select
            v-model="editAgentMCPTools"
            multiple
            filterable
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="3"
            placeholder="请选择关联工具"
            class="tools-select"
            :loading="isLoadingTools"
        >
          <el-option
              v-for="item in mcpTools"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          ></el-option>
        </el-select>
        <div class="form-item-tip" v-if="editAgentMCPTools.length > 0">已选择 {{ editAgentMCPTools.length }} 项</div>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="agent-dialog-footer">
        <el-button @click="isEditAgentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdateAgent">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.chat-container {
  display: flex;
  height: 100%;
  background: transparent;
  position: relative;
  gap: 24px;
  padding: 24px;
}

.topics-sidebar {
  width: 280px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  border-radius: 16px;
  display: flex;
  flex-direction: column;
  position: relative;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(0, 0, 0, 0.03);
  overflow: hidden;
}

.topics-sidebar::after {
  content: "";
  position: absolute;
  top: 0;
  right: 0;
  width: 100%;
  height: 100%;
  background-image: linear-gradient(135deg, rgba(79, 70, 229, 0.03) 0%, rgba(79, 70, 229, 0.01) 100%);
  pointer-events: none;
}

.topics-header {
  padding: 20px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  background: rgba(255, 255, 255, 0.8);
}

.topics-header h2 {
  margin: 0 0 16px 0;
  font-size: 18px;
  color: #1a1a1a;
  font-weight: 600;
}

.new-topic-btn {
  width: 100%;
  padding: 10px 16px;
  background: linear-gradient(135deg, #4f46e5, #7c3aed);
  color: white;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.new-topic-btn:hover {
  transform: translateY(-1px);
  background: linear-gradient(135deg, #4338ca, #6d28d9);
  box-shadow: 0 6px 16px rgba(79, 70, 229, 0.3);
}

.topics-list {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 20px;
}

.topic-item {
  padding: 12px 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
  color: #4b5563;
  border-bottom: 1px solid rgba(0, 0, 0, 0.03);
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 8px;
}

.topic-content {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
  min-width: 0;
}

.topic-icon {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  background: rgba(99, 102, 241, 0.1);
  color: #6366f1;
  flex-shrink: 0;
}

.topic-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
  min-width: 0;
}

.topic-title {
  font-size: 14px;
  color: #1a1a1a;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.topic-status {
  font-size: 12px;
  color: #6366f1;
  font-weight: 500;
}

.topic-item.active {
  background: linear-gradient(135deg, rgba(99, 102, 241, 0.1), rgba(139, 92, 246, 0.1));
}

.topic-item.active .topic-icon {
  background: rgba(99, 102, 241, 0.2);
}

.topic-item.active .topic-title {
  color: #4f46e5;
}

.topic-item.default-topic .topic-icon {
  background: rgba(107, 114, 128, 0.1);
  color: #6b7280;
}

.topic-item.default-topic .topic-title {
  color: #6b7280;
}

.delete-topic-icon {
  opacity: 0;
  transition: all 0.3s ease;
  color: #ef4444;
  padding: 4px;
  border-radius: 4px;
  flex-shrink: 0;
}

.topic-item:hover .delete-topic-icon {
  opacity: 1;
}

.delete-topic-icon:hover {
  background: rgba(239, 68, 68, 0.1);
}

.chat-main {
  flex: 1;
  display: flex;
  justify-content: center;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(0, 0, 0, 0.03);
  overflow: hidden;
}

.chat-content {
  width: 100%;
  max-width: 1000px;
  display: flex;
  flex-direction: column;
  position: relative;
  height: calc(100% - 40px);
  margin-top: 20px;
}

.chat-messages {
  flex: 1;
  padding: 44px;
  overflow-y: auto;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  gap: 16px;
  min-height: 0;
  scroll-behavior: smooth; /* 添加平滑滚动效果 */
}

.message {
  max-width: 65%;
  margin-bottom: 16px;
  padding: 12px 16px;
  border-radius: 12px;
  background: rgba(79, 70, 229, 0.08);
  color: #1a1a1a;
  font-size: 14px;
  line-height: 1.6;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
  border: 1px solid rgba(79, 70, 229, 0.1);
  position: relative;
}

.message:not(.user-message) {
  padding-bottom: 24px; /* 为打字机动画留出空间 */
}

.message:not(.user-message)::after {
  content: '';
  position: absolute;
  bottom: 8px;
  right: 8px;
  width: 8px;
  height: 8px;
  background: linear-gradient(135deg, #6366f1, #8b5cf6);
  border-radius: 50%;
  animation: typing 1s infinite;
  display: none; /* 默认隐藏 */
}

.message:not(.user-message).loading::after {
  display: block; /* 只在loading状态时显示 */
}

@keyframes typing {
  0% {
    opacity: 0.3;
    transform: scale(0.8);
  }
  50% {
    opacity: 1;
    transform: scale(1);
  }
  100% {
    opacity: 0.3;
    transform: scale(0.8);
  }
}

.user-message {
  margin-left: auto;
  background-color: white;
  color: #1a1a1a;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.message:not(.user-message) {
  position: relative;
  background: rgba(79, 70, 229, 0.05);
  border: 1px solid rgba(79, 70, 229, 0.1);
}

.message:not(.user-message)::before {
  content: '';
  position: absolute;
  left: -8px;
  top: 50%;
  width: 0;
  height: 0;
  border: 8px solid transparent;
  border-right-color: rgba(79, 70, 229, 0.05);
  transform: translateY(-50%);
}

.user-message::before {
  content: '';
  position: absolute;
  right: -8px;
  top: 50%;
  width: 0;
  height: 0;
  border: 8px solid transparent;
  border-left-color: white;
  transform: translateY(-50%);
}

.chat-input {
  padding: 20px;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  display: flex;
  gap: 16px;
  align-items: flex-end;
  position: relative;
  box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.02);
  min-height: 100px;
  margin-top: auto;
}

.chat-input::after {
  content: "";
  position: absolute;
  top: 0;
  right: 0;
  width: 100%;
  height: 100%;
  background-image: linear-gradient(135deg, rgba(255, 255, 255, 0.08) 0%, rgba(255, 255, 255, 0.03) 100%);
  pointer-events: none;
}

.input-area {
  flex: 1;
  position: relative;
  background: #f8f9fa;
  border-radius: 12px;
  padding: 4px;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05);
  width: calc(100% - 8px);
}

.input-area textarea {
  width: 100%;
  min-height: 24px;
  max-height: 200px;
  padding: 12px 16px;
  border: none;
  border-radius: 8px;
  outline: none;
  font-size: 14px;
  line-height: 1.6;
  resize: none;
  background: transparent;
  transition: all 0.2s ease;
  color: #1a1a1a;
  box-sizing: border-box;
}

.input-area textarea:focus {
  box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.2);
  outline: none;
}

.input-area textarea::placeholder {
  color: #9ca3af;
}

.send-button {
  width: 44px;
  height: 44px;
  background: linear-gradient(135deg, #4f46e5, #7c3aed);
  color: white;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  box-shadow: 0 2px 8px rgba(79, 70, 229, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
  flex-shrink: 0;
}

.send-button:hover {
  transform: translateY(-2px);
  background: linear-gradient(135deg, #4338ca, #6d28d9);
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.3);
}

.send-button:active {
  transform: translateY(0);
  background: linear-gradient(135deg, #3730a3, #5b21b6);
  box-shadow: 0 2px 6px rgba(79, 70, 229, 0.2);
}

.send-button::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.15) 0%, rgba(255, 255, 255, 0) 50%, rgba(255, 255, 255, 0.15) 100%);
  transform: translateX(-100%);
  transition: transform 0.6s ease;
}

.send-button:hover::after {
  transform: translateX(100%);
}

.send-button:disabled {
  background: linear-gradient(135deg, #e5e7eb, #d1d5db);
  cursor: not-allowed;
  box-shadow: none;
  transform: none;
}

.send-button .is-loading {
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 隐藏滚动条但保持滚动功能 */
::-webkit-scrollbar {
  display: none;
}

/* Firefox */
* {
  scrollbar-width: none;
}

.settings-section {
  padding: 20px;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
  margin-top: auto;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.settings-btn {
  width: 100%;
  padding: 10px 16px;
  background: transparent;
  color: #4b5563;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.settings-btn:hover {
  background: rgba(79, 70, 229, 0.05);
  color: #4f46e5;
}

.settings-btn .el-icon {
  font-size: 16px;
  transition: transform 0.3s ease;
}

.settings-btn:hover .el-icon {
  transform: rotate(90deg);
}

.settings-btn span {
  margin-left: 4px;
}

.model-service-btn {
  background: transparent;
}

.model-service-btn:hover {
  background: linear-gradient(135deg, rgba(99, 102, 241, 0.1), rgba(139, 92, 246, 0.1));
}

.clear-chat-btn {
  color: #ef4444;
}

.clear-chat-btn:hover {
  background: rgba(239, 68, 68, 0.05);
  color: #dc2626;
}

.clear-chat-btn .el-icon {
  color: inherit;
}

.top-selectors {
  position: absolute;
  top: 24px;
  right: 24px;
  display: flex;
  flex-direction: row-reverse;
  gap: 16px;
  z-index: 10;
}

.agent-selector {
  position: relative;
  width: auto;
}

.agent-selector-ai {
  position: relative;
  width: auto;
}

.agent-select-wrapper {
  position: relative;
}

.agent-select-content {
  position: relative;
}

.agent-select-input {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 16px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(0, 0, 0, 0.03);
  white-space: nowrap;
  margin: 10px 10px;
}

.agent-select-input:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
  background: linear-gradient(135deg,
  rgba(255, 255, 255, 0.98) 0%,
  rgba(255, 255, 255, 0.95) 100%
  );
}

.agent-label {
  font-size: 14px;
  font-weight: 600;
  color: #1a1a1a;
  background: linear-gradient(135deg, #6366f1, #8b5cf6);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}

.agent-indicator {
  display: flex;
  align-items: center;
  gap: 6px;
}

.agent-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-left: 8px;
  background: linear-gradient(135deg, #10b981, #34d399);
  box-shadow: 0 0 12px rgba(16, 185, 129, 0.4);
  animation: pulse 2s infinite;
}

.agent-dot.enabled {
  background: linear-gradient(135deg, #10b981, #34d399);
  box-shadow: 0 0 8px rgba(16, 185, 129, 0.4);
}

.agent-dot.disabled {
  background: linear-gradient(135deg, #ef4444, #f87171);
  box-shadow: 0 0 8px rgba(239, 68, 68, 0.4);
}

.agent-status {
  font-size: 12px;
  color: #6b7280;
}

.dropdown-icon {
  font-size: 14px;
  color: #6366f1;
  transition: transform 0.3s ease;
}

.agent-select-input:hover .dropdown-icon {
  transform: rotate(180deg);
}

.agent-dropdown {
  position: absolute;
  top: 100%;
  right: 0;
  margin-top: 8px;
  background: rgba(255, 255, 255, 0.98);
  backdrop-filter: blur(16px);
  -webkit-backdrop-filter: blur(16px);
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(0, 0, 0, 0.05);
  min-width: 240px;
  overflow: hidden;
  animation: dropdownAppear 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
}

@keyframes dropdownAppear {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.agent-option {
  padding: 12px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.agent-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  flex: 1;
  margin-right: 40px;
  cursor: pointer;
}

.agent-actions {
  display: flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.3s ease;
  position: absolute;
  right: 30px;
  top: 50%;
  transform: translateY(-50%);
  background: rgba(255, 255, 255, 0.9);
  padding: 4px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.agent-option:hover .agent-actions {
  opacity: 1;
}

.action-icon {
  font-size: 16px;
  color: #6b7280;
  cursor: pointer;
  transition: all 0.3s ease;
  padding: 4px;
  border-radius: 4px;
}

.action-icon:hover {
  background: rgba(0, 0, 0, 0.05);
}

.edit-icon:hover {
  color: #6366f1;
}

.delete-icon:hover {
  color: #ef4444;
}

.agent-name {
  font-size: 14px;
  font-weight: 600;
  color: #1a1a1a;
}

.agent-desc {
  font-size: 12px;
  color: #6b7280;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}

.agent-status-indicator {
  display: flex;
  align-items: center;
  gap: 6px;
}

.status-dot {
  width: 6px;
  height: 6px;
  background: linear-gradient(135deg, #10b981, #34d399);
  border-radius: 50%;
  box-shadow: 0 0 6px rgba(16, 185, 129, 0.3);
}

.status-text {
  font-size: 12px;
  color: #6b7280;
}

.agent-option.selected {
  background: linear-gradient(135deg,
  rgba(99, 102, 241, 0.1),
  rgba(139, 92, 246, 0.1)
  );
}

.agent-option.selected .agent-name {
  color: #6366f1;
}

.agent-option.selected::after {
  content: '';
  position: absolute;
  right: 16px;
  width: 8px;
  height: 8px;
  background: linear-gradient(135deg, #6366f1, #8b5cf6);
  border-radius: 50%;
  box-shadow: 0 0 12px rgba(99, 102, 241, 0.4);
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(99, 102, 241, 0.4);
  }
  70% {
    box-shadow: 0 0 0 8px rgba(99, 102, 241, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(99, 102, 241, 0);
  }
}

.add-agent-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #6366f1;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
  margin-top: 8px;
}

.add-agent-btn:hover {
  background: linear-gradient(135deg,
  rgba(99, 102, 241, 0.05),
  rgba(139, 92, 246, 0.05)
  );
  color: #4f46e5;
}

.add-agent-btn .el-icon {
  font-size: 16px;
}

.add-agent-dialog {
  :deep(.el-dialog) {
    background: rgba(255, 255, 255, 0.98);
    backdrop-filter: blur(16px);
    -webkit-backdrop-filter: blur(16px);
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    border: 1px solid rgba(0, 0, 0, 0.05);
    width: 500px !important;
  }

  :deep(.el-dialog__header) {
    padding: 20px;
    margin: 0;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
    position: relative;
  }

  :deep(.el-dialog__title) {
    font-size: 18px;
    font-weight: 600;
    color: #1a1a1a;
    position: relative;
    padding-left: 12px;
  }

  :deep(.el-dialog__title::before) {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 4px;
    height: 16px;
    background: linear-gradient(135deg, #6366f1, #8b5cf6);
    border-radius: 2px;
  }

  :deep(.el-dialog__body) {
    padding: 24px;
  }

  :deep(.el-dialog__footer) {
    padding: 16px 24px;
    border-top: 1px solid rgba(0, 0, 0, 0.05);
  }

  :deep(.el-form-item__label) {
    font-size: 14px;
    color: #4b5563;
    font-weight: 500;
    padding-bottom: 8px;
  }

  :deep(.el-input__wrapper) {
    background: rgba(255, 255, 255, 0.8);
    border: 1px solid rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    box-shadow: none;
    transition: all 0.3s ease;
  }

  :deep(.el-input__wrapper:hover) {
    border-color: rgba(99, 102, 241, 0.3);
  }

  :deep(.el-input__wrapper.is-focus) {
    border-color: #6366f1;
    box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.1);
  }

  :deep(.el-textarea__inner) {
    background: rgba(255, 255, 255, 0.8);
    border: 1px solid rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    min-height: 80px;
    padding: 12px 16px;
    transition: all 0.3s ease;
  }

  :deep(.el-textarea__inner:hover) {
    border-color: rgba(99, 102, 241, 0.3);
  }

  :deep(.el-textarea__inner:focus) {
    border-color: #6366f1;
    box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.1);
  }

  :deep(.el-switch) {
    --el-switch-on-color: #6366f1;
    --el-switch-off-color: #e5e7eb;
  }

  :deep(.el-select) {
    width: 100%;
  }

  :deep(.el-select__wrapper) {
    background: rgba(255, 255, 255, 0.8);
    border: 1px solid rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    box-shadow: none;
    transition: all 0.3s ease;
  }

  :deep(.el-select__wrapper:hover) {
    border-color: rgba(99, 102, 241, 0.3);
  }

  :deep(.el-select__wrapper.is-focus) {
    border-color: #6366f1;
    box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.1);
  }

  :deep(.el-select-dropdown__item) {
    padding: 8px 16px;
    transition: all 0.3s ease;
  }

  :deep(.el-select-dropdown__item:hover) {
    background: rgba(99, 102, 241, 0.05);
  }

  :deep(.el-select-dropdown__item.selected) {
    background: rgba(99, 102, 241, 0.1);
    color: #6366f1;
    font-weight: 500;
  }

  :deep(.el-tag) {
    background: rgba(99, 102, 241, 0.1);
    border-color: rgba(99, 102, 241, 0.2);
    color: #6366f1;
    border-radius: 4px;
  }

  :deep(.el-tag__close) {
    color: #6366f1;
  }

  :deep(.el-tag__close:hover) {
    background-color: rgba(99, 102, 241, 0.2);
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.cancel-btn {
  padding: 8px 16px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  background: transparent;
  color: #4b5563;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  background: rgba(0, 0, 0, 0.05);
  transform: translateY(-1px);
}

.confirm-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 8px;
  background: linear-gradient(135deg, #6366f1, #4f46e5);
  color: white;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(99, 102, 241, 0.2);
}

.confirm-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3);
}

.confirm-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(99, 102, 241, 0.2);
}

.form-switch {
  margin-top: 8px;
}

.form-select {
  width: 100%;
  margin-top: 8px;
}

.form-select :deep(.el-select__tags) {
  max-height: 100px;
  overflow-y: auto;
}

.form-select :deep(.el-select__tags::-webkit-scrollbar) {
  width: 6px;
}

.form-select :deep(.el-select__tags::-webkit-scrollbar-track) {
  background: rgba(99, 102, 241, 0.1);
  border-radius: 3px;
}

.form-select :deep(.el-select__tags::-webkit-scrollbar-thumb) {
  background: rgba(99, 102, 241, 0.3);
  border-radius: 3px;
}

.form-select :deep(.el-select__tags::-webkit-scrollbar-thumb:hover) {
  background: rgba(99, 102, 241, 0.4);
}

.agent-option.disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.agent-option.disabled .agent-name {
  color: #9ca3af;
}

.agent-option.disabled .agent-desc {
  color: #9ca3af;
}

.agent-option.disabled .agent-info {
  cursor: not-allowed;
}

.edit-agent-dialog {
  :deep(.el-dialog) {
    background: rgba(255, 255, 255, 0.98);
    backdrop-filter: blur(16px);
    -webkit-backdrop-filter: blur(16px);
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    border: 1px solid rgba(0, 0, 0, 0.05);
    width: 500px !important;
  }
}

.md-preview {
  background: transparent;
  padding: 0;
  margin: 0;
}

.md-preview :deep(.md-editor-preview-wrapper) {
  padding: 0;
  background: transparent;
}

.md-preview :deep(.md-editor-preview) {
  padding: 0;
  background: transparent;
}

.md-preview :deep(p) {
  margin: 0;
  padding: 0;
}

.md-preview :deep(pre) {
  margin: 0;
  padding: 0;
  background: transparent;
}

.md-preview :deep(code) {
  background: transparent;
  padding: 0;
}

.agent-dialog {
  :deep(.el-dialog) {
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
    border: 1px solid rgba(0, 0, 0, 0.04);
    overflow: hidden;
    width: 520px !important;
  }
  
  :deep(.el-dialog__header) {
    display: none;
  }
  
  :deep(.el-dialog__body) {
    padding: 0;
  }
  
  :deep(.el-dialog__footer) {
    padding: 16px 24px;
    border-top: 1px solid #f0f0f0;
    background: #f9fafb;
  }
}

.agent-dialog-header {
  padding: 20px 24px 0;
}

.agent-dialog-title {
  margin-bottom: 16px;
}

.agent-dialog-title h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
}

.agent-form {
  padding: 0 24px 20px;
}

.agent-form :deep(.el-form-item) {
  margin-bottom: 20px;
}

.agent-form :deep(.el-form-item__label) {
  font-size: 14px;
  color: #374151;
  font-weight: 500;
  padding-bottom: 8px;
  line-height: 1.2;
}

.agent-form :deep(.el-input__wrapper),
.agent-form :deep(.el-textarea__inner) {
  box-shadow: none;
  border: 1px solid #e5e7eb;
  background: #fff;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.agent-form :deep(.el-input__wrapper:hover),
.agent-form :deep(.el-textarea__inner:hover) {
  border-color: #6366f1;
}

.agent-form :deep(.el-input__wrapper.is-focus),
.agent-form :deep(.el-textarea__inner:focus) {
  border-color: #6366f1;
  box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.1);
}

.form-item-tip {
  font-size: 12px;
  color: #6b7280;
  margin-top: 6px;
  text-align: right;
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 16px;
}

.tools-select {
  width: 100%;
}

.tools-select :deep(.el-select__wrapper) {
  box-shadow: none;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  background: #fff;
  transition: all 0.2s ease;
}

.tools-select :deep(.el-select__wrapper:hover) {
  border-color: #6366f1;
}

.tools-select :deep(.el-select__wrapper.is-focus) {
  border-color: #6366f1;
  box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.1);
}

.agent-dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.agent-dialog-footer .el-button {
  padding: 8px 16px;
  font-size: 14px;
}

.agent-dialog-footer .el-button--primary {
  background-color: #6366f1;
  border-color: #6366f1;
}

.agent-dialog-footer .el-button--primary:hover {
  background-color: #4f46e5;
  border-color: #4f46e5;
}

.tool-calls-section {
  margin-bottom: 12px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid rgba(99, 102, 241, 0.2);
  background: rgba(99, 102, 241, 0.05);
}

.tool-call-item {
  margin-bottom: 1px;
}

.tool-call-item:last-child {
  margin-bottom: 0;
}

.tool-call-header {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background: rgba(99, 102, 241, 0.1);
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.tool-call-header:hover {
  background: rgba(99, 102, 241, 0.15);
}

.tool-icon {
  margin-right: 8px;
  color: #6366f1;
  font-size: 14px;
  transition: transform 0.2s ease;
}

.tool-name {
  font-weight: 500;
  color: #4f46e5;
  font-size: 14px;
}

.tool-call-content {
  padding: 12px;
  background: rgba(255, 255, 255, 0.7);
  border-top: 1px solid rgba(99, 102, 241, 0.1);
}

.tool-args {
  margin: 0;
  white-space: pre-wrap;
  word-break: break-all;
  font-family: monospace;
  font-size: 13px;
  line-height: 1.5;
  color: #374151;
  background: transparent;
  overflow-x: auto;
  max-height: 300px;
  overflow-y: auto;
}
</style>